﻿#########################################################################
## Process Torrent Files - Accepts Filename as Parameter  COMPLETE     ##
#########################################################################
param([string]$PathToProcess = "")
$CompletedTorrentDir = "\\VM001TO\Torrents\Complete"
$UnsortedTorrentDir = "\\VM001TO\Torrents\ToSort"
$Logfile = "\\VM001TO\Torrents\TorrentProcessor.log"
$TV = "\\DS001ST\STORAGE\Video\TV Shows\"
$PornS = "\\DS001ST\STORAGE\Video\Other\Sorted\Specific Series\"
$PornU = "\\DS001ST\STORAGE\Video\Other\Other\$(get-date -Format yyyy)\"
$Movies = "\\DS001ST\STORAGE\Video\Movies\"

function Add-LogEntry {
	param([string]$LogText, [string]$LogSeverity)
	if ($LogSeverity -eq "INFO") {
		$LogColour = "Yellow"
	}
	elseif ($LogSeverity -eq "WARNING"){
		$LogColour = "Red"
	}
	elseif ($LogSeverity -eq "INPUT"){
		$LogColour = "Green"
	}
	Write-Host "$(Get-Date -Format g) --> ($($LogSeverity)) $($LogText)" -ForegroundColor $LogColour
	Add-Content $Logfile "$(Get-Date -Format g) --> ($($LogSeverity)) $($LogText)"
}

if ($PathToProcess -ne ""){
	#We have a file to process so we'll assume uTorrent is running this
	$FilesToProcess = Get-ChildItem -LiteralPath $CompletedTorrentDir\$PathToProcess -Recurse -Exclude @("*.r[0-9][0-9]", "*.sfv","*.nfo","*sample*")
	Add-LogEntry "We are processing torrent file $($PathToProcess)" "INFO"
	
	foreach ($FileToProcess in $FilesToProcess){
		if ($FileToProcess -like "*.rar"){
			#We'll UnRar this file
			Add-LogEntry "$FileToProcess UNRARING To $UnsortedTorrentDir" "INFO"
			& 'C:\Program Files\WinRAR\UnRar.exe' e -y $FileToProcess $UnsortedTorrentDir
		}
		else {
			#We'll just copy it
			Add-LogEntry "$FileToProcess COPYING To $UnsortedTorrentDir" "INFO"
			Copy-Item -LiteralPath $FileToProcess -Destination $UnsortedTorrentDir
		}
	}
}
else{
	#There are no files to process - we will be running scoring on the current files
	Add-LogEntry "Torrent Processor is being run without parameters, we will now begin the scoring process" "INFO"
	$FilesToScore = Get-ChildItem $UnsortedTorrentDir -Recurse -Exclude @("*.r[0-9][0-9]", "*.sfv","*.nfo","*sample*") | where { ! $_.PSIsContainer }
	$FinalCopyList = @{}
	
	#Lets build our keyword search list
	#These are our lists of keywords
	$TVShows = Get-ChildItem $TV | where {$_.PSIsContainer}
	$PornSeries = Get-ChildItem $PornS | where {$_.PSIsContainer}
	$VideoKeyWords = @()
	foreach ($TVShow in $TVShows) {
	    $IndividualKeywords = $TVShow.Name.Split(" ,.")
	    foreach ($IndividualKeyword in $IndividualKeywords) {
	        $VideoKeyWords += ,@($IndividualKeyword, $TVShow.Name,"TV")
	    } 
	}
	foreach ($PornSerie in $PornSeries) {
	    $IndividualKeywords = $PornSerie.Name.Split(" ,.")
	    foreach ($IndividualKeyword in $IndividualKeywords) {
	   		$VideoKeyWords += ,@($IndividualKeyword, $PornSerie.Name,"PornS")
	    }
	}
	
	
	#OK lets process each individual file
	foreach ($FileToScore in $FilesToScore) {
		$MatchedName = ""
		$NewFileName = ""
		$FileToScoreObject = Get-ChildItem $FileToScore
		$FileToScoreKeywordsWK = $($FileToScore.Name).Split(" ,.\")
		$FileToScoreKeywords = @($FileToScoreKeywordsWK | Where-Object {@('and','the','to','an','i','we','your') -notcontains $_})
		$FileMatches = @()
		foreach ($VideoKeyword in $VideoKeyWords){
		    if ($FileToScoreKeywords -eq $VideoKeyword[0]){
		        $FileMatches += ,@($VideoKeyword[1], $VideoKeyword[2])
		    }

		}
		if ($FileMatches.Count -eq 0) {
		    Add-LogEntry "$($FileToScore): I Couldn't Find a match for this file in a TV or Porn series, is this a (M)ovie or (U)nsorted Porn?" "INPUT"
		    $NoMatchResult = Read-Host "(M) or (U)"
		    if ($NoMatchResult -eq "m"){
		    #It's a movie, we'll have to sort that out
				$MatchedType = "Movies"
				$FileNameChange = Read-Host "Do you want to change the filename from $($FileToScore)? (Y)yes or (N)o" 
				if ($FileNameChange  -eq "Y") {
					$NewFileName = Read-Host "New Filename:"
					if ($NewFileName -eq ""){
						Add-LogEntry  "Must Enter a value!" "WARNING"
					}
		    	}
				elseif ($FileNameChange  -eq "N") {
					$NewFileName = "$($FileToScore.Name)"
				}
			
		    }
		    elseif ($NoMatchResult -eq "u"){
		        $MatchedType = "PornU"
		    }
		    else {
		        Add-LogEntry "Input Invalid" "WARNING"
		    }
		}
		else {
		    #We have matches, lets count them an make sure we have a winner
		    $FileMatchGroup = $FileMatches | Group-Object | Sort-Object Count -DESCENDING
		    if ($($FileMatchGroup | Measure).Count -eq 1) {
		        $MatchedName = $FileMatchGroup.Group[0][0]
		        $MatchedType = $FileMatchGroup.Group[0][1]
		        Add-LogEntry "$($FileToScore): This item has a match with $MatchedName (Unique)" "INFO"
		    }
		    else {
		        #We're going to have to do some more work to determine the winner
		        if ($FileMatchGroup[1].Count -eq $FileMatchGroup[0].Count) {
		            #We cannot determine a winner
		            Add-LogEntry "$($FileToScore): Sorry - but I cannot score this file, you'll have to do it manually (Equal Scores)" "WARNING"
		        }
		        else {
		            #The first entry had a higher score, so lets go with that
		            $MatchedName = $FileMatchGroup[0].Group[0][0]
		            $MatchedType = $FileMatchGroup[0].Group[0][1]
		            Add-LogEntry "$($FileToScore): This item has a match with $MatchedName (Higher Score)" "INFO"
		        }
		        
		    }
		}
		
		if ($MatchedType -eq "TV") {
		    #we have to do some more work to determine the season
		    [string]$SeasonEpString = $FileToScoreKeywords -like "S*E*"
		    [int]$SeasonNumber = $($SeasonEpString.Split("SE"))[1]
			$DirectoryToCopyTo = (Get-Variable $MatchedType).Value + "$MatchedName\Season $SeasonNumber"
			$FinalFileNameToCopy = $($FileToScoreObject.Name)
		}
		elseif ($MatchedType -eq "Movies"){
			$FinalFileNameToCopy = $NewFileName
			$MoviePath = switch -regex ("$($FinalFileNameToCopy.Substring(0,1))")
				{
					"[1-10]" {"1-10"}
					"[A-C]" {"A-C"}
					"[D-G]" {"D-G"}
					"[H-K]" {"H-K"}
					"[L-P]" {"L-P"}
					"[R-S]" {"R-S"}
					"[T-U]" {"T-U"}
					"[V-Z]" {"V-Z"}
				}
			$DirectoryToCopyTo = (Get-Variable $MatchedType).Value + "$MoviePath"
		}
		else {
			$DirectoryToCopyTo = (Get-Variable $MatchedType).Value + "$MatchedName"
			$FinalFileNameToCopy = $($FileToScoreObject.Name)
		}
		
		#Now, we need to find out if we want to copy the file
		
		Add-LogEntry "########DO YOU WANT TO MOVE THIS FILE?##########" "INPUT"
		Add-LogEntry "Original Location: $($FileToScore)" "INPUT"
		Add-LogEntry "New Location: $($DirectoryToCopyTo)\$FinalFileNameToCopy" "INPUT"
		
		$CopyResult = Read-Host "Enter (Y)es or (N)o "
		if ($CopyResult -eq "Y") {
			$FinalCopyList.Add("$($FileToScore)", "$($DirectoryToCopyTo)\$($FinalFileNameToCopy)")
		    Add-LogEntry "$($DirectoryToCopyTo)\$FinalFileToCopy - Copied" "INFO"
		}
		elseif ($CopyResult -eq "N") {
		    Add-LogEntry "You chose not to Move" "WARN"
		}

	
	}
	Add-LogEntry "Final copy list is below" "INPUT"
	$FinalCopyList | Format-Table -AutoSize
	$CopyBegin = Read-Host "Do you want to begin the copy process? (Y)es or (N)o"
	if ($CopyBegin -eq "Y") {
		Add-LogEntry "Beginning Moving Process" "INFO"
		
		foreach ($FinalCopy in $FinalCopyList.GetEnumerator()){
			Move-Item "$($FinalCopy.Key)" "$($FinalCopy.Value)"
			Add-LogEntry "Moved item to $($FinalCopy.Value)" "INFO"
		}
		
	}
	else {
		Add-LogEntry "Move Cancelled" "WARNING"
	}
	
	
	#This is the end of processing for the scoring
}
